package com.mall.order.mq.delay;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author hanshuai
 * @version 1.0
 * @description @TODO
 * @date 2021/12/15 19:33
 */
@Component
@Slf4j
public class DelayOrderProducer {
    private DefaultMQProducer producer;

    //初始化
    @PostConstruct
    public void init(){
        try {
            producer = new DefaultMQProducer("delayOrderProducer");
            producer.setNamesrvAddr("127.0.0.1:9876");
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * 延迟未支付自动取消
     * @param orderId
     * @return
     */
    public boolean sendDelayOrder(String orderId){
        SendResult sendRes =null;
      try{
          Message message = new Message();
          message.setTopic("delayOrder");
          message.setBody(orderId.getBytes("utf-8"));
          message.setDelayTimeLevel(10);
          log.info(orderId+" 设置延迟订单");
          //开启
          sendRes = producer.send(message);
      }catch (Exception e){
            e.printStackTrace();
      }
      if (sendRes!=null && SendStatus.SEND_OK.equals(sendRes.getSendStatus())){
          return true;
      }
      return false;
    }
}
